<?php

require dirname(__FILE__) . '/../twl-php/autoload.php';

try {

    $filename = Consolium::getArgumentValue('--file');
    $resizeto = Consolium::getArgumentValue('--resizeto');

    $ftp    = Consolium::getArgumentValue('--ftp');
    $http   = Consolium::getArgumentValue('--http');
    $ljUser = Consolium::getArgumentValue('--ljuser');
    $ljPass = Consolium::getArgumentValue('--ljpass');

    if (!preg_match('~ftp://([^:]*):(.*)@([^/]+)(.*)~', $ftp, $arrMatches))
        throw new ConsoleArgumentException("incorrect $ftp");

    list($null, $ftpuser, $ftppass, $ftpserver, $ftpfolder) = $arrMatches;

    $app = new OneclickLjPost($filename);

    if ($resizeto) {
        $app->resize($resizeto);
    }

    $app->upload($ftpserver, $ftpuser, $ftppass, $ftpfolder);
    $app->post($ljUser, $ljPass, $http);

} catch (ConsoleArgumentException $e) {
    echo $e->getMessage() . "
Usage: " . Consolium::getProgramName() . " --file filename [--resizeto <max width/height>] --ftp ftp://user:pass@server/folder --http http://server/folder --ljuser user --ljpass pass

";
} catch (Exception $e) {
    echo "### " . $e->getMessage() . "\n";
    //echo $e->getTraceAsString();
}

class OneclickLjPost {

    private $arrFiles;
    private $filesPrefix = '';
    private $arrFilesToDelete = array();

    public function __construct($file) {

        if (is_dir($file)) {

            $this->arrFiles = array_filter(
                Dir::getFiles($file),
                array('Image', 'isSupportedFile')
            );

            $this->filesPrefix = basename($file) . '-';

        } else {
            $this->arrFiles = array($file);
        }
    }

    public function resize($resizeto) {

        foreach ($this->arrFiles as &$filename) {

            echo "resize $filename\n";

            $img = Image::load($filename);
            $img->resizeIscribe($resizeto, $resizeto);

            $filename = Env::getTmpDir() . basename($filename);
            $img->saveAs($filename);

            $this->arrFilesToDelete[] = $filename;
        }
    }

    public function __destruct() {
        foreach ($this->arrFilesToDelete as $filename) {
            echo "delete temporary file $filename\n";
            File::delete($filename);
        }
    }

    public function upload($ftpserver, $ftpuser, $ftppass, $ftpfolder) {

        $oConnect = new FtpConnect($ftpserver, $ftpuser, $ftppass);
        $oConnect->chDir($ftpfolder);

        foreach ($this->arrFiles as $filename) {
            echo "upload $filename (" . File::getHumanSize($filename) . ") => " . $this->getRemoteFilename($filename) . " \n";
            $oConnect->uploadFile($filename, $this->getRemoteFilename($filename));
        }
    }

    private function getRemoteFilename($filename) {
        return $this->filesPrefix . basename($filename);
    }

    public function post($ljUser, $ljPass, $http) {

        $text = $this->genImgTag($http, reset($this->arrFiles));

        if ($arrOthersFiles = array_slice($this->arrFiles, 1)) {

            $text .= "\n\n<lj-cut>";

            foreach ($arrOthersFiles as $filename) {
                $text .= $this->genImgTag($http, $filename) . "\n\n";
            }

            $text .= "</lj-cut>";
        }

        //echo $text . "\n";

        $lj = new LjClient($ljUser, $ljPass);

        $post = new LjPost();
        $post->setText($text);
        $post->setDate(Date::createCurrent()->increaseHours(1));

        $lj->post($post);
    }

    private function genImgTag($http, $filename) {

        $src = Dir::addEndslash($http) . $this->getRemoteFilename(basename($filename));
        $alt = basename($filename) . ', ' .  File::getHumanSize($filename);

        return '<img src="' . $src. '" alt="' . $alt  . '">';
    }

}


?>